
package com.michaelwolf.mytool.wcfcompmanger.wcfanalyzer;

import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import org.w3c.dom.Node;

import com.michaelwolf.mytool.wcfcompmanger.wcfanalyzer.WCFLoader.TraverseCacheData;
import com.sun.org.apache.xerces.internal.dom.DeferredAttrImpl;

public class NodeDenpendcyFinder implements AttributesHandler {
	
	private static boolean AVOIDING_ENDLESS_LOOP = false;

	@Override
	public void process(Node attrnode, TraverseCacheData traverseCacheData, String moduleName) {
		// parameter 
		Map<String, Node> componentIdMap = traverseCacheData.getComponentIdMap();
		Map<String, Map<String, String>> stringPropertiesMap = traverseCacheData.getStringPropertiesMap();
		Map<String, String> stringModuleProMap = stringPropertiesMap.get(moduleName);
		
		// result
		Map<Node, Set<Node>> dependencyMap = traverseCacheData.getDependencyMap();
		Map<String, Set<Node>> stringUsedToNodeMap = traverseCacheData.getStringUsedToNodeMap();
		
		String nodeValue = attrnode.getNodeValue();
		
		DeferredAttrImpl attr = (DeferredAttrImpl)attrnode;
		Node owner = attr.getOwnerElement();
		String ownerNodeName = owner.getNodeName();
		
		
		if(componentIdMap.containsKey(nodeValue) || 
				("icon-ref".equals(ownerNodeName) && componentIdMap.containsKey("icon-"+nodeValue))){
			
			if("next-page".equals(ownerNodeName) && AVOIDING_ENDLESS_LOOP){
				return;
			}
			
			Node usedNode = null;
			if("icon-ref".equals(ownerNodeName)){
				usedNode = componentIdMap.get("icon-"+nodeValue);
			}else{
				usedNode = componentIdMap.get(nodeValue);
			}
			
			Set<Node> useNodeSet = dependencyMap.get(usedNode);
			if(useNodeSet == null){
				useNodeSet = new HashSet<Node>();
				dependencyMap.put(usedNode, useNodeSet);
			}
			Node compNode = NodeHandler.getOwnerCompNode(attrnode);
			if(compNode!=null){
				useNodeSet.add(NodeHandler.getOwnerCompNode(attrnode));
			}
			
		}
		
		if(stringModuleProMap.containsKey(nodeValue)){
			String proString = stringModuleProMap.get(nodeValue);
			Set<Node> strUseNodeSet = stringUsedToNodeMap.get(proString);
			if(strUseNodeSet == null){
				strUseNodeSet = new HashSet<Node>();
				stringUsedToNodeMap.put(proString, strUseNodeSet);
			}
			
			strUseNodeSet.add(attrnode);
			
		}
		
	}

}
